//
//  MyPhotoViewController.m
//  Bespoke
//
//  Created by Cheng on 12/9/6.
//
//

#import "MyPhotoViewController.h"
#import "HomePageViewController.h"
#import "Crop.h"
#import "Split.h"

#define IMAGEVIEW_WIDTH 1024
#define IMAGEVIEW_HEIGHT 704

@implementation MyPhotoViewController
@synthesize Tb_CameraAction,IVw_MyPhoto,delegate,Image_MyPhoto,popoverController;
@synthesize Array_AccountInfo,ND_MyPhoto,NS_MyPhotoName,NS_PhotoType,VC_Controller;
@synthesize Vw_CreateBook, Vw_EditMyPhoto, BK_En_object;

-(IBAction)close:(id)sender
{
    [popoverController dismissPopoverAnimated:YES];
    [self.delegate MyPhotoViewControllerDidClose:self];
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    
    IVw_MyPhoto.image = [Image_MyPhoto SetImageSize:IMAGEVIEW_WIDTH Height:IMAGEVIEW_HEIGHT];
    
    if (Image_MyPhoto!=nil) {
        BBI_SaveToMyBoard.enabled = YES;//Enable SaveToMyBoard.
    }
}

- (void)viewDidAppear:(BOOL)animated {
    
    //Compress photo.
    for (float compressionQuality=1.0; compressionQuality>0; compressionQuality=compressionQuality-0.1) {
        
        ND_MyPhoto = UIImageJPEGRepresentation([IVw_MyPhoto.image fixOrientation],compressionQuality);
        if ([ND_MyPhoto length]<200000) {
            break;
        }
    }
    
    if (Image_MyPhoto==nil) {
        [self PhotoLibrary];
    }
}

- (IBAction)SelectPhotoToLibrary:(id)sender {
    if (popoverController==nil)
        [self PhotoLibrary];
    else {
        [popoverController dismissPopoverAnimated:YES];
        popoverController = nil;
    }
}

- (IBAction)SaveToMyBoard:(id)sender {
    
    if (Vw_EditMyPhoto == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"EditMyPhoto" owner:self options:nil];
        
        Vw_EditMyPhoto.frame = CGRectMake(307, 171, Vw_EditMyPhoto.frame.size.width, Vw_EditMyPhoto.frame.size.height);
        
        UIColor *Cyan = [UIColor colorWithRed:189.0/255.0 green:228.0/255.0 blue:229.0/255.0 alpha:1.0];
        [Vw_EditMyPhoto.Bt_MyBoard setTitleColor:Cyan forState:UIControlStateNormal];
        [Vw_EditMyPhoto.Bt_Cancel setTitleColor:Cyan forState:UIControlStateNormal];
        
        Vw_EditMyPhoto.delegate = self;
        
    }
    [Vw_EditMyPhoto initArray:((AccountInfo *)[self.Array_AccountInfo objectAtIndex:0]).MyBoard.BoardArray];
    Vw_EditMyPhoto.Array_AccountInfo = self.Array_AccountInfo;
    [Vw_EditMyPhoto OpenEditMyPhoto:Array_AccountInfo GetPhoto:ND_MyPhoto GetPhotoName:NS_MyPhotoName GetPhotoType:NS_PhotoType];
    
    [Vw_EditMyPhoto setAlpha:0];
    [UIView animateWithDuration:0.5
                     animations:^{[Vw_EditMyPhoto setAlpha:1.0];[self.view addSubview:Vw_EditMyPhoto];}
                     completion:^(BOOL finished){ }];
}

- (void)PhotoLibrary {
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
    
        UIImagePickerController *imagePickController = [[UIImagePickerController alloc]init];
    
        imagePickController.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
        imagePickController.delegate = self;
        
        UIPopoverController *popover=[[UIPopoverController alloc] initWithContentViewController:imagePickController];
        popoverController = popover;
    
        [popoverController presentPopoverFromBarButtonItem:BBI_PhotoLibraryLocation permittedArrowDirections:UIPopoverArrowDirectionDown animated:YES];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    if ([mediaType isEqualToString:@"public.image"]) {  //Check Source is image.
        UIImage *Image_Photo = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        
        //Get photo name.
        NSURL *imagePath = [info objectForKey:@"UIImagePickerControllerReferenceURL"];
        NSString *NS_ImageName = [imagePath absoluteString];
        
        IVw_MyPhoto.image = [Image_Photo SetImageSize:IMAGEVIEW_WIDTH Height:IMAGEVIEW_HEIGHT];
        
        //Compress photo.
        for (float compressionQuality=1.0; compressionQuality>0; compressionQuality=compressionQuality-0.1) {
            
            ND_MyPhoto = UIImageJPEGRepresentation([IVw_MyPhoto.image fixOrientation],compressionQuality);
            if ([ND_MyPhoto length]<200000) {
                break;
            }
        }
        
        //Parse ID
        NS_MyPhotoName = [NSString stringWithFormat:@"%@.jpg",[NS_ImageName StringSplit:@"id=([^&]+)"]];
        
        //Parse TYPE
        NS_PhotoType = [NS_ImageName StringSplit:@"ext=([^&]+)"];
        
        [popoverController dismissPopoverAnimated:YES];
        popoverController = nil;
        
        //Enable SaveToMyBoard.
        BBI_SaveToMyBoard.enabled = YES;
    }
}

#pragma mark - Interface Orientation Management

//For iOS 5
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return ((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (interfaceOrientation == UIInterfaceOrientationLandscapeRight));
}

//For iOS 6
-(BOOL)shouldAutorotate {
    return YES;
}

-(NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscape;
}

#pragma mark - EditMyPhotoDelegate

- (void)uiViewTouched_EditMyPhoto:(BOOL)wasInSide {
    if(!wasInSide) {
        [Vw_EditMyPhoto removeFromSuperview];
    }
}

- (void)PhotoSaveSuccess:(NSString *)BoardName {
    [Vw_EditMyPhoto removeFromSuperview];
    [popoverController dismissPopoverAnimated:YES];
    [self.delegate MyPhotoViewControllerDidSave:self BoardName:BoardName];
}

- (void)CreatedNewBookPressed {
    
    [Vw_EditMyPhoto removeFromSuperview];
    
    if (Vw_CreateBook == nil) {
        Vw_CreateBook = [[[NSBundle mainBundle] loadNibNamed:@"CreateBookView" owner:self options:nil] objectAtIndex:0];
        Vw_CreateBook.frame = CGRectMake(self.view.bounds.size.width/2-self.Vw_CreateBook.frame.size.width/2,
                                         self.view.bounds.size.height/2-self.Vw_CreateBook.frame.size.height/2,
                                         self.Vw_CreateBook.frame.size.width,
                                         self.Vw_CreateBook.frame.size.height);
        
        Vw_CreateBook.BK_En_object = self.BK_En_object;
        
        Vw_CreateBook.delegate = self;
        Vw_CreateBook.Tf_BookName.delegate = Vw_CreateBook;
    }
    Vw_CreateBook.AMB_MyBoard = [[self.Array_AccountInfo objectAtIndex:0] MyBoard];
    
    [Vw_CreateBook setAlpha:0];
    [UIView animateWithDuration:0.5
                     animations:^{[Vw_CreateBook setAlpha:1.0];[self.view addSubview:Vw_CreateBook];}
                     completion:^(BOOL finished){ }];
}

#pragma mark - CreateBookViewDelegate

-(void)uiViewCancel {
    
    [Vw_CreateBook removeFromSuperview];
}

-(void) ViewDidCreated {
    
    [Vw_CreateBook removeFromSuperview];
    
    NSMutableArray *Array_Board = ((AccountInfo *)[self.Array_AccountInfo objectAtIndex:0]).MyBoard.BoardArray;
    
    [self.Vw_EditMyPhoto initArray:Array_Board];
    [self.Vw_EditMyPhoto.Bt_MyBoard setTitle:((AccountBoard *)[Array_Board lastObject]).name forState:UIControlStateNormal];
    self.Vw_EditMyPhoto.Bt_MyBoard.tag = ((AccountBoard *)[Array_Board lastObject]).BoardID;
    self.Vw_EditMyPhoto.Row_selected = Array_Board.count-1;
    
    [UIView animateWithDuration:0.5
                     animations:^{[Vw_EditMyPhoto setAlpha:1.0];[self.view addSubview:Vw_EditMyPhoto];}
                     completion:^(BOOL finished){ }];
}

@end
